<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>回到顶部</title>
		<style type="text/css">
			#to_top{
				width: 30px;
				height: 40px;
				font: 14px/20px arial;
				text-align: center;
				background-color: #06c;
				position: fixed;
				cursor: pointer;
				color: #fff;
				right: 200px;
				bottom: 100px;
			}
		</style>
	</head>
	<body style="height: 2000px;">
		<div id="to_top">返回顶部</div>
	</body>
	
	<script type="text/javascript" src="../js/jquery-3.6.0.js"></script>
	<script type="text/javascript">
		$('#to_top').click(function(){
			//瞬间滚到顶部
			// $('html,body').scrollTop(0)
			
			// 平滑滚到顶部
			  // 总距离
			  var $page = $('html,body')
			  var distance = $('html').scrollTop() + $('body').scrollTop()
			  // 总时间
			  var time = 500
			  // 间隔时间
			  var intervalTime = 50
			  var itemDistance = distance/(time/intervalTime)
			
			// 使用循环定时器不断滚动
			var intervalld = setInterval(function(){
				distance -= itemDistance
				// 到达顶部,停止定时器
				if(distance<=0){
					distance = 0//修正
					clearInterval(intervalId)
				}
				$page.scrollTop(distance)
			}, intervalTime)		
		})
	</script>
</html>
